/**
 * 
 */
package com.moorecat.app;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.moorecat.MooerApplication;
import com.moorecat.R;
import com.moorecat.bean.Shop;
import com.moorecat.bean.User;
import com.moorecat.http.HttpUtils;
import com.moorecat.utils.ui.ProgressLinearLayout;
import com.moorecat.utils.ui.UiUtils;

/**
 * 我的关注
 * 
 * @author Minglong.Yu
 * @version 1.0
 * @created Jun 25, 2011 12:48:59 AM
 */
public class MyFollow extends Activity implements OnItemClickListener,
		OnClickListener, OnScrollListener {
	private static final String TAG = "MyFollow";
	private ListView listView;
	private ProgressLinearLayout footer;
	private BusinessAdapter businessAdapter;
	private List<Shop> shopList = new ArrayList<Shop>();
	private ImageView searchBtn;
	private EditText edit;
	private MooerApplication mooerApp;
	private long taskId;
	private User user;
	private boolean isLoaded, isSearching;

	private int limit = 20, limitStart = 0;

	private boolean loadOver, loading, isCancelled;

	private AsyncTask bitmapTask;

	private String search;

	private int count;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.my_follow);
		mooerApp = (MooerApplication) getApplication();
		searchBtn = (ImageView) findViewById(R.id.search_btn);
		searchBtn.setOnClickListener(this);
		edit = (EditText) findViewById(R.id.search);
		listView = (ListView) findViewById(R.id.listview);
		search = getIntent().getStringExtra("search");
		if (search == null || "".equals(search.trim())) {
			search = "";
		}
		edit.setText(search);
		footer = (ProgressLinearLayout) LayoutInflater.from(this).inflate(
				R.layout.progress_small, null);
		footer.initView();
		listView.addFooterView(footer);
		businessAdapter = new BusinessAdapter(this, shopList, false);
		listView.setAdapter(businessAdapter);
		listView.setOnItemClickListener(this);
		listView.setOnScrollListener(this);
		edit.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView paramTextView, int paramInt,
					KeyEvent paramKeyEvent) {
				if (edit.getText().toString().length() > 0) {
					shopList.clear();
					businessAdapter.notifyDataSetChanged();
					isSearching = true;
					search = edit.getText().toString();
					if (search == null || "".equals(search.trim())) {
						search = "";
					}
					footer.initView();
					listView.addFooterView(footer);
					new BusinessMyFollowListTask().execute(
							String.valueOf(user.getId()), search);
					InputMethodManager imm = (InputMethodManager) MyFollow.this
							.getSystemService(Context.INPUT_METHOD_SERVICE);

					if (imm.isActive()) {

						imm.hideSoftInputFromWindow(
								edit.getApplicationWindowToken(), 0);
					}
				} else {
					UiUtils.showToast(MyFollow.this, "请输入您要搜索的关键字");
				}
				return false;
			}
		});
		user = mooerApp.getUser();
		if (!mooerApp.isLoggedin() || user == null || user.getId() < 1) {
			Intent intent = new Intent(this, MoreAccountSetting.class);
			intent.putExtra("isFinish", true);
			startActivity(intent);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		count++;
		user = mooerApp.getUser();
		if (mooerApp.isLoggedin() && !isLoaded) {
			footer.setVisibility(View.VISIBLE, View.VISIBLE, View.GONE,
					View.GONE);
			search = edit.getText().toString();
			if (search == null || "".equals(search.trim())) {
				search = "";
			}
			new BusinessMyFollowListTask().execute(
					String.valueOf(user.getId()), search);
			isLoaded = true;
		} else {
			if (count > 1 && !mooerApp.isLoggedin()) {
				finish();
			}
			// footer.setVisibility(View.GONE, View.GONE, View.VISIBLE,
			// View.GONE);
			// footer.setText(null, "请先登录");
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
        if (!shopList.isEmpty()) {
            Shop shop = shopList.get(position).copy();
            Intent intent = new Intent(this, Business.class);
            intent.putExtra("businessInfo", shop);
            intent.putExtra("isFollow", true);
            startActivity(intent);
        }
	}

	@Override
	public void onClick(View v) {
		if (v == searchBtn) {
			if (edit.getText().toString().length() > 0) {
				shopList.clear();
				businessAdapter.notifyDataSetChanged();
				isSearching = true;
				search = edit.getText().toString();
				if (search == null || "".equals(search.trim())) {
					search = "";
				}
				footer.setVisibility(View.VISIBLE, View.VISIBLE, View.GONE,
						View.GONE);
				listView.addFooterView(footer);
				new BusinessMyFollowListTask().execute(
						String.valueOf(user.getId()), search);
			} else {
				UiUtils.showToast(this, "请输入您要搜索的关键字");
			}
		}

	}

	public class BusinessMyFollowListTask extends
			AsyncTask<String, Integer, List<Shop>> {

		private boolean isException;

		@Override
		protected List<Shop> doInBackground(String... params) {
			loading = true;
			List<Shop> list = null;
			try {
				list = HttpUtils.fetchFollowedShopList(
						Integer.parseInt(params[0]), params[1], limitStart,
						limit);
				for (Shop shop : list) {
					shop.setIcon(mooerApp.getShopListDefaultIcon());
				}
			} catch (Exception e) {
				isException = true;
				e.printStackTrace();
			}
			return list;
		}

		@Override
		protected void onPostExecute(List<Shop> result) {
			super.onPostExecute(result);
			loading = false;
			isSearching = false;
			if (isException) {
				footer.setText(null, "加载失败");
				footer.setVisibility(View.GONE, View.GONE, View.VISIBLE,
						View.VISIBLE);
			} else {
				if (result.size() > 0) {
					if (result.size() < limit) {
						listView.removeFooterView(footer);
					}
					shopList.addAll(result);
					businessAdapter.notifyDataSetChanged();
					bitmapTask = new BitmapTask().execute("");
				} else {
					if (limitStart == 0) {
						footer.setVisibility(View.GONE, View.GONE,
								View.VISIBLE, View.GONE);
						footer.setText(null, "暂无关注的商家列表");
					} else {
						loadOver = true;
						listView.removeFooterView(footer);
						Log.i(TAG, "ListView load over");
					}
				}
			}
		}

	}

	private class BitmapTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... params) {
			long id = System.currentTimeMillis();
			taskId = id;
			// 增加一个缓存List避免列表长度变化时遍历发生错误
			List<Shop> cacheList = new ArrayList<Shop>();
			cacheList.addAll(shopList);
			Iterator<Shop> it = cacheList.iterator();
			while (it.hasNext()) {
				/*
				 * 避免重复下载,如果有新的线程,则停止老的线程
				 */
				if (id != taskId || isCancelled) {
					break;
				}
				Shop shop = it.next();
				Bitmap icon = null;
				try {
					if (shop.getIcon() == mooerApp.getShopListDefaultIcon()) {
						if (shop.getLogo() != null
								&& !"".equals(shop.getLogo())) {
							icon = HttpUtils.downloadBitmap(shop.getLogo());
							if (icon != null) {
								shop.setIcon(icon);
								publishProgress(0);
							}
						}
					}
				} catch (Exception e) {

				}
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			businessAdapter.notifyDataSetChanged();
		}

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (shopList.size() == 0) {
			return;
		}
		if (view.getLastVisiblePosition() == view.getCount() - 1) {
			if (view.getCount() < limitStart || loadOver || loading) {
				Log.d(TAG, view.getCount() + "|" + limitStart + "| load over");
				return;
			}
			limitStart = limitStart + limit;
			limit = 5;
			if (search == null) {
				search = "";
			}
			new BusinessMyFollowListTask().execute(
					String.valueOf(user.getId()), search);
		}
		if (loadOver) {
			listView.removeFooterView(footer);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (bitmapTask != null) {
			boolean isSuccess = bitmapTask.cancel(true);
			Log.i(TAG, "BitmapTask cancelled " + isSuccess);
			isCancelled = true;
		}
	}
}
